package ui.swing.common;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Enumeration;

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class SwingUtil {

	public static final void setLookAndFeel() {
		Font font = new Font("Dialog", Font.PLAIN, 12);
		Enumeration keys = UIManager.getLookAndFeelDefaults().keys();
		/** 定义Windows风格界面 * */
		while (keys.hasMoreElements()) {
			Object key = keys.nextElement();
			if (UIManager.get(key) instanceof Font) {
				UIManager.put(key, font);
			}
		}
		try {
			UIManager
					.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception el) {
			System.out.println("设置LookAndFeel时出现错误！");
			el.printStackTrace();
		}
	}

	/**
	 * 功能: 自动调节表格宽度
	 * @author 林可  2010-5-24 下午01:50:33
	 * @param table
	 */
	public static void adjustColumnPreferredWidths(JTable table) {
		// 取某列最宽的Component，将这列的preferredSize设成其宽度
		TableColumnModel columnModel = table.getColumnModel();
		for (int col = 0; col < table.getColumnCount(); col++) {
			int maxwidth = 0;
			TableCellRenderer rend = table.getCellRenderer(10000, col);
			for (int row = 0; row < table.getRowCount(); row++) {
				// TableCellRenderer rend = table.getCellRenderer(row, col);
				Object value = table.getValueAt(row, col);
				Component comp = rend.getTableCellRendererComponent(table,
						value, false, false, row, col);
				maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
			} // for row

			// -- then we should take column header into consideration --
			TableColumn column = columnModel.getColumn(col);
			// 1.先取得当前column的HeaderRenderer（也是TableCellRenderer实例）
			TableCellRenderer headerRenderer = column.getHeaderRenderer();
			if (headerRenderer == null)
				headerRenderer = table.getTableHeader().getDefaultRenderer();

			// 2.再取得rendererComponent
			Object headerValue = column.getHeaderValue();
			Component headerComp = headerRenderer
					.getTableCellRendererComponent(table, headerValue, false,
							false, 0, col);

			// 3.再参与比较
			maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width);

			// 4.最后结果
			column.setPreferredWidth(maxwidth);
		} // for col
	}

	public static void runderAlternateColorTable(JTable table,
			Color[] colorsToRenderer) {
		int columnCount = table.getColumnCount();
		AlternateRowColorTableCellRenderer renderer = new AlternateRowColorTableCellRenderer(colorsToRenderer);
		for (int colIndex = 0; colIndex < columnCount; colIndex++) {
			TableColumn tc = table.getColumnModel().getColumn(colIndex);
			tc.setCellRenderer(renderer);
		}
		table.revalidate();
		table.repaint();
	}

	public static String title(Object o) {
		String t = o.getClass().toString();
		// Remove the word "class":
		// if(t.indexOf("class")!=-1)
		// t = t.substring(6);
		return t.replaceAll("^class\\b\\s*", "");
		// 单词边界 空白
		// return t;
	}

	public static void run(JFrame frame, int width, int height) {
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.setSize(width, height);
		frame.setVisible(true);
	}

	public static void run(JApplet applet, int width, int height) {
		JFrame frame = new JFrame(title(applet));
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.getContentPane().add(applet);
		frame.setSize(width, height);
		applet.init();
		applet.start();
		frame.setVisible(true);
	}

	public static void run(JPanel panel, int width, int height) {
		JFrame frame = new JFrame(title(panel));
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.getContentPane().add(panel);
		frame.setSize(width, height);
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		System.out.println(title(new JFrame("")));
	}

	private static class ColorLooper {

		private int length;

		private Color[] colors;

		public ColorLooper(Color[] colors) {
			// 保护性拷贝
			this.colors = new Color[colors.length];
			System.arraycopy(colors, 0, this.colors, 0, colors.length);
			if (colors.length == 0)
				throw new IllegalArgumentException("颜色参数不合法");
			this.length = colors.length;
		}

		public Color getColor4Row(int rowIndex) {
			return colors[rowIndex % length];
		}
	}

	private static class AlternateRowColorTableCellRenderer extends
			DefaultTableCellRenderer implements TableCellRenderer {
		
		private ColorLooper colorLooper;
		
		public AlternateRowColorTableCellRenderer(Color[] colors) {
			this.colorLooper = new ColorLooper(colors);
		}

		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			comp.setBackground(colorLooper.getColor4Row(row));
			return comp;
		}

	}

}
